package com.jeedcp.shiro.sys.controller;


import com.jeedcp.core.aspect.annotation.LogOperationAno;
import com.jeedcp.core.common.JsonResult;
import com.jeedcp.core.common.Status;
import com.jeedcp.shiro.util.Encryptor;
import com.jeedcp.core.util.Base64Util;
import com.jeedcp.core.util.ConvertUtils;
import com.jeedcp.core.validator.ValidatorUtils;
import com.jeedcp.shiro.jwt.JwtUtil;
import com.jeedcp.shiro.sys.dto.PasswordDTO;
import com.jeedcp.shiro.sys.dto.UserDto;
import com.jeedcp.shiro.sys.entity.User;
import com.jeedcp.shiro.sys.service.IUserService;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

import com.jeedcp.core.controller.BaseController;

/**
 * <p>
 * 用户表 前端控制器
 * </p>
 *
 * @author caochaofeng
 * @since 2019-08-15
 */
@RestController
@RequestMapping("/sys/user")
@Slf4j
public class UserController extends BaseController<IUserService, User,UserDto> {


    @GetMapping("info")
    @ApiOperation("登录用户信息")
    public JsonResult<UserDto> info(){
        UserDto data = ConvertUtils.sourceToTarget(JwtUtil.getCurrentUser(), UserDto.class);
        return new JsonResult<UserDto>().ok(data);
    }

    @PostMapping("password")
    @ApiOperation("修改密码")
    @LogOperationAno("修改密码")
    public JsonResult password(@RequestBody PasswordDTO dto) throws Exception {
        //效验数据
        ValidatorUtils.validateEntity(dto);
        String password = Base64Util.decodeThreeTimes(dto.getPassword());
        String newPassword = Base64Util.decodeThreeTimes(dto.getNewPassword());

        User user = JwtUtil.getCurrentUser();
        //原密码不正确
        if (!user.getPassword().equals(Encryptor.encryptPassword(password, user.getSalt()))) {
            log.warn(user.getRealName()+"修改密码错误，原密码不正确");
            return new JsonResult().error(Status.PASSWORD_ERROR.code());
        }
        user.setPassword(Encryptor.encryptPassword(newPassword, user.getSalt()));
        baseService.updateById(user);
        log.debug(user.getRealName()+"修改密码成功");
        return new JsonResult();
    }

}
